<?php
define('DB_HOSTNAME', 'localhost');
define('DB_USERNAME', '<user>');
define('DB_PASSWORD', '<pass>');
define('DB_DATABASE', 'minecraft');
define('AUTHS_DB_PATH', '/home/minecraft/server/plugins/AuthMe/auths.db');

$auths = file(AUTHS_DB_PATH, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);

echo 'Loaded ' . count($auths) . ' lines.' . PHP_EOL;

$db = new MySQLi(DB_HOSTNAME, DB_USERNAME, DB_PASSWORD, DB_DATABASE); //, 3306, '/usr/local/mysqld/var/mysql.sock'
$selectStmt = $db -> prepare('SELECT player_id FROM lvm_players WHERE LOWER(login_name) = ?');
$updateStmt = $db -> prepare(
	'UPDATE lvm_players p
	LEFT JOIN lvm_player_settings s ON p.player_id = s.player_id
	SET p.ip_address = ?,
	p.salt = ?,
	s.password = ?
	WHERE p.player_id = ?');

$selectStmt -> bind_result($playerId);

foreach ($auths as $auth) {
	$chunks = explode(':', $auth);
	$selectStmt -> bind_param('s', $chunks[0]);
	$selectStmt -> execute();
	$selectStmt -> store_result();

	if ($selectStmt -> num_rows > 0) {
		echo 'Found ' . $selectStmt -> num_rows . ' row(s) for player ' . $chunks[0] . '.';
		if ($selectStmt -> num_rows > 1) {
			echo ' Skipping.';
			continue;
		}
		echo PHP_EOL;
	} else {
		echo 'Could not find player ' . $chunks[0] . PHP_EOL;
		continue;
	}

	$selectStmt -> fetch();

	list(,,$salt, $hash) = explode('$', $chunks[1]);
	$longIp = ip2long($chunks[2]);

	echo 'Updating player ' . $playerId . ' with IP ' . $longIp . ' (' . $chunks[2] . '), hash ' .
		$hash . ' and salt ' . $salt . '.' . PHP_EOL;

	$updateStmt -> bind_param('issi', $longIp, $salt, $hash, $playerId);
	$updateStmt -> execute();
}